package GUILayer;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;

import java.awt.event.MouseAdapter;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Set;

import java.util.Date;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

import ControlLayer.ProductCtr;
import ControlLayer.SaleCtr;
import ModelLayer.Product;
import ModelLayer.Sale;
import ModelLayer.SaleLine;

public class SaleGUI extends JPanel implements ActionListener{
	/**
     * 
     */
	private static final long serialVersionUID = 1L;

	private SaleCtr saleCtr;
	private ProductCtr productCtr;

	private JPanel menuLeftPanel;
	private JPanel menuRightPanel;
	private JPanel salePanel;
	private JPanel showAllSalePanel;
	private JPanel createSalePanel;
	private JPanel createSaleLeftPanel;
	private JPanel createSaleRightPanel;

	private JPanel showSalePanel;
	private JPanel showSaleLeftPanel;
	private JPanel showSaleRightPanel;
	private JPanel saleInfoPanel = new JPanel();
	private JPanel saleChoicePanel = new JPanel();

	private JButton btnSearch;
	private JButton btnCreateSaleMenu;
	private JButton btnCreateSale;
	private JButton btnCancelSale = new JButton("Cancel");
	private JButton btnAddSaleline = new JButton("Add");
	private JButton btnDeleteSaleline = new JButton("Delete");

	private JTextField textField_saleIdMenu = new JTextField();
	private JTextField textField_saleId;
	private JTextField textField_customerId;
	private JTextField textField_invoiceId;
	private JTextField textField_date;
	private JTextField textField_deliveryStatus;
	private JTextField textField_deliveryDate;
	private JTextField textField_ProductId;
	private JTextField textField_ProductQuantity;
	private JComboBox cbbDeliveryStatus;
	private String[] listStrings = { "NotDelivered", "IsDelivered", "IsReturned" };

	private JLabel lblSaleId = new JLabel("Sale Id:");
	private JLabel lblCustomerId = new JLabel("Customer Id:");
	private JLabel lblDate = new JLabel("Date(dd/mm/yyyy):");
	private JLabel lblInvoiceId = new JLabel("Invoice Id:");
	private JLabel lblDeliveryDate = new JLabel("Delivery Date(dd/mm/yyyy):");
	private JLabel lblDeliveryStatus = new JLabel("Delivery Status:");

	private DefaultTableModel saleTableModel = new DefaultTableModel();
	private DefaultTableModel saleLineTableModel = new DefaultTableModel();
	private JScrollPane saleTableScrollPane;
	private JScrollPane salelineScrollPane;
	private JTable showAllSaleTable;
	private JTable showSalelineTable;

	private double totalPrice;

	private Date date;
	private Date deliveryDate;
	private HashMap<Integer, Integer> products;

	public SaleGUI() {
		saleCtr = new SaleCtr();
		productCtr = new ProductCtr();
		products = new HashMap<Integer, Integer>();
		totalPrice = 0;
		initialize();
	}

	public void initialize() {
		this.setLayout(new BorderLayout());

		// top menu with search and create function
		JPanel menuPanel = new JPanel();
		menuPanel.setLayout(new BorderLayout());
		menuPanel.setBorder(BorderFactory.createTitledBorder("Sale Menu"));
		this.add(menuPanel, BorderLayout.NORTH);

		JLabel lblSaleIdMenu = new JLabel("Sale Id:");
		textField_saleIdMenu.setColumns(8);
		btnSearch = new JButton("Search");
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int saleId;
				products = new HashMap<Integer, Integer>();
				try {
					saleId = Integer.parseInt(textField_saleIdMenu.getText());
					showSale(saleId);
				} catch (NumberFormatException e1) {
					JOptionPane.showMessageDialog(null, "Please input number",
							"Error", JOptionPane.ERROR_MESSAGE);

				}
			}
		});

		// add search in menu
		menuLeftPanel = new JPanel();
		menuLeftPanel.setLayout(new FlowLayout());
		menuPanel.add(menuLeftPanel, BorderLayout.WEST);

		menuRightPanel = new JPanel();
		menuRightPanel.setLayout(new FlowLayout());
		menuPanel.add(menuRightPanel, BorderLayout.EAST);

		menuLeftPanel.add(lblSaleIdMenu);
		menuLeftPanel.add(textField_saleIdMenu);
		menuLeftPanel.add(btnSearch);

		// add create button in menu
		btnCreateSaleMenu = new JButton("Create Sale");
		btnCreateSaleMenu.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					createSale();
					products = new HashMap<Integer, Integer>();
				} catch (ParseException e1) {

					e1.printStackTrace();
				}
			}
		});
		menuRightPanel.add(btnCreateSaleMenu);

		// add panels in salePanel cardlayout
		salePanel = new JPanel();
		salePanel.setLayout(new CardLayout());
		this.add(salePanel, BorderLayout.CENTER);

		showAllSalePanel = new JPanel();
		salePanel.add("showAllSalePanel", showAllSalePanel);
		showAllSalePanel.setLayout(new BoxLayout(showAllSalePanel,
				BoxLayout.X_AXIS));
		showAllSalePanel.setBorder(BorderFactory
				.createTitledBorder("All Sales"));

		// make show all sales table
		addSaleTable();
		showAllSale();

		// make create offer panel
		createSalePanel = new JPanel();
		createSalePanel.setLayout(new GridLayout(1, 2));

		// make create offer left panel
		createSaleLeftPanel = new JPanel();
		createSaleLeftPanel.setLayout(new BoxLayout(createSaleLeftPanel,
				BoxLayout.Y_AXIS));
		createSaleRightPanel = new JPanel();
		createSaleRightPanel.setLayout(new BoxLayout(createSaleRightPanel,
				BoxLayout.Y_AXIS));
		createSaleRightPanel.setBorder(BorderFactory
				.createTitledBorder("SaleLine"));
		createSalePanel.add(createSaleLeftPanel);
		createSalePanel.add(createSaleRightPanel);
		salePanel.add(createSalePanel, "createSalePanel");

		// make show one sale panel
		showSalePanel = new JPanel();

		showSalePanel.setLayout(new GridLayout(1, 2));

		showSaleLeftPanel = new JPanel();
		showSaleLeftPanel.setLayout(new BoxLayout(showSaleLeftPanel,
				BoxLayout.Y_AXIS));

		showSaleRightPanel = new JPanel();
		showSaleRightPanel.setLayout(new BoxLayout(showSaleRightPanel,
				BoxLayout.Y_AXIS));
		showSaleRightPanel.setBorder(BorderFactory
				.createTitledBorder("SaleLines"));

		showSalePanel.add(showSaleLeftPanel);
		showSalePanel.add(showSaleRightPanel);
		salePanel.add(showSalePanel, "showSalePanel");
		

	}

	public boolean showSale(int saleId) {
		boolean success = true;
		Sale sale = null;
		try {
			if (saleId != 0) {
				sale = saleCtr.getSale(saleId);
			}
		} catch (NumberFormatException e) {
			success = false;
			JOptionPane.showMessageDialog(null, "Please input Number", "Error",
					JOptionPane.ERROR_MESSAGE);
			return success;
		} catch (Exception e) {
			success = false;
			JOptionPane.showMessageDialog(null, e, "Error",
					JOptionPane.ERROR_MESSAGE);
			return success;
		}
		if (success) {
			JPanel saleInfoPanel1 = createSaleInfoPanel();

			showSaleLeftPanel.removeAll();
			showSaleLeftPanel.add(saleInfoPanel1);
			JPanel saleChoicePanel = createSaleChoicePanel();
			showSaleLeftPanel.add(saleChoicePanel);
			
			showSaleRightPanel.removeAll();
			showSaleRightPanel.add(showSalelineTable());

			setSaleInfo(sale);

			ArrayList<SaleLine> salelines = saleCtr.getSaleLinesForSale(sale
					.getSaleId());
			products = new HashMap<Integer, Integer>();

			// store saleline in local object
			for (SaleLine saleline : salelines) {
				products.put(saleline.getProduct().getProductId(),
						saleline.getQuantity());
			}

			showSaleline();
		}
		
		JPanel salelineChoicePanel = new JPanel();
		salelineChoicePanel.setLayout(new FlowLayout());
		showSaleRightPanel.add(salelineChoicePanel);

		btnAddSaleline = new JButton("Add");
		btnAddSaleline.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				EventQueue.invokeLater(new Runnable() {
					public void run() {
						try {
							JFrame addSalelineFrame = addSalelinePopupWindow();
							addSalelineFrame.setVisible(true);
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
				});

			}
		});

		btnDeleteSaleline = new JButton("Delete");
		btnDeleteSaleline.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				EventQueue.invokeLater(new Runnable() {
					public void run() {
						try {
							JFrame deleteSalelineFrame = deleteSalelinePopupWindow();
							deleteSalelineFrame.setVisible(true);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			}
		});

		salelineChoicePanel.add(btnAddSaleline);
		salelineChoicePanel.add(btnDeleteSaleline);
		
		CardLayout cl = (CardLayout) salePanel.getLayout();
		cl.show(salePanel, "showSalePanel");

		return success;
	}

	private void setSaleInfo(Sale sale) {
		
		textField_saleId.setText(Integer.toString(sale.getSaleId()));
		textField_customerId.setText(Integer.toString(sale.getCustomer()
				.getId()));
		textField_invoiceId.setText(Integer.toString(sale.getInvoice()
				.getInvoiceNo()));
		textField_date.setText(new SimpleDateFormat("dd/MM/yyyy").format(sale
				.getDate()));
		selectDeliveryType(sale.getDeliverStatus().toString());
		textField_deliveryDate.setText(new SimpleDateFormat("dd/MM/yyyy")
				.format(sale.getDeliveryDate()));
	}

	private JPanel createSaleChoicePanel() {
		JPanel saleChoicePanel = new JPanel();
		saleChoicePanel.setLayout(new FlowLayout());

		JButton btnDeleteSale = new JButton("Delete");
		btnDeleteSale.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				deleteSaleActionPerformed(e);
				textField_saleIdMenu.setText("");
				
			}
		});

		JButton btnCancelSale = new JButton("Cancel");
		btnCancelSale.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				showAllSale();
				textField_saleIdMenu.setText("");

			}
		});

		JButton btnSaveSale = new JButton("Save");
		btnSaveSale.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// saveSaleActionPerformed(e);
				try {
					String deliveryStatus = listStrings[cbbDeliveryStatus
					          						.getSelectedIndex()];
					Date deliveryDate = new SimpleDateFormat("dd/MM/yyyy")
							.parse(textField_deliveryDate.getText());
					Date date = new SimpleDateFormat("dd/MM/yyyy")
					.parse(textField_date.getText());
					
					saleCtr.updateSale(Integer.parseInt(textField_saleIdMenu.getText()), Integer.parseInt(textField_invoiceId
							.getText()), date, deliveryDate,
							deliveryStatus,  Integer
									.parseInt(textField_customerId
											.getText()), totalPrice, products);
					JOptionPane.showMessageDialog(null, "The sale is saved.",
							"Save Sale", JOptionPane.INFORMATION_MESSAGE);	
					
				} catch (NumberFormatException e1) {
					JOptionPane.showMessageDialog(null,
							"Please input correct value", "Error",
							JOptionPane.ERROR_MESSAGE);
				} catch (ParseException e1) {
					JOptionPane.showMessageDialog(null,
							"Please input correct value", "Error",
							JOptionPane.ERROR_MESSAGE);
					e1.printStackTrace();
				} catch (Exception e1) {
					JOptionPane.showMessageDialog(null,
							"Please input correct value", "Error",
							JOptionPane.ERROR_MESSAGE);
				}
				
				showAllSale();
				cleanTextField();
				

			}
		});

		saleChoicePanel.add(btnSaveSale);
		saleChoicePanel.add(btnDeleteSale);
		saleChoicePanel.add(btnCancelSale);

		return saleChoicePanel;
	}

	public void createSale() throws ParseException {
		createSaleLeftPanel.removeAll();

		// add saleInfoPanel
		JPanel saleInfoPanel = createSaleInfoPanel();
		textField_date.setText(convertDate(getCurrentDate()));
		textField_date.setEditable(false);

		createSaleLeftPanel.add(saleInfoPanel);

		// add sale choice panel
		JPanel createSaleChoicePanel = new JPanel();
		createSaleChoicePanel.setLayout(new FlowLayout());
		createSaleLeftPanel.add(createSaleChoicePanel);

		btnCancelSale.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				showAllSale();

			}
		});
		btnCreateSale = new JButton("Save");
		date = Calendar.getInstance().getTime();

		btnCreateSale.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {

				try {
					try {
						String deliveryStatus = listStrings[cbbDeliveryStatus
						          						.getSelectedIndex()];
						deliveryDate = new SimpleDateFormat("dd/MM/yyyy")
								.parse(textField_deliveryDate.getText());
						saleCtr.createSale(Integer.parseInt(textField_invoiceId
								.getText()), date, deliveryDate, totalPrice,
								deliveryStatus, Integer
										.parseInt(textField_customerId
												.getText()), products);
					} catch (NumberFormatException e1) {
						JOptionPane.showMessageDialog(null,
								"Please input number", "Error",
								JOptionPane.ERROR_MESSAGE);
					}

					JOptionPane.showMessageDialog(null, "The sale is created.",
							"Create Sale", JOptionPane.INFORMATION_MESSAGE);

					showAllSale();
				} catch (Exception e1) {
					JOptionPane.showMessageDialog(null, e1, "Error",
							JOptionPane.ERROR_MESSAGE);
				}
			}
		});

		createSaleChoicePanel.add(btnCancelSale);
		createSaleChoicePanel.add(btnCreateSale);

		// add saleline table
		createSaleRightPanel.removeAll();

		salelineScrollPane = showSalelineTable();
		JPanel showSalelinePanel = new JPanel();
		showSalelinePanel.setLayout(new BoxLayout(showSalelinePanel,
				BoxLayout.X_AXIS));
		showSalelinePanel.add(salelineScrollPane);
		createSaleRightPanel.add(showSalelinePanel);

		// add saleline choice panel
		JPanel salelineChoicePanel = new JPanel();
		salelineChoicePanel.setLayout(new FlowLayout());
		createSaleRightPanel.add(salelineChoicePanel);

		btnAddSaleline = new JButton("Add");
		btnAddSaleline.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				EventQueue.invokeLater(new Runnable() {
					public void run() {
						try {
							JFrame addSalelineFrame = addSalelinePopupWindow();
							addSalelineFrame.setVisible(true);
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
				});

			}
		});

		btnDeleteSaleline = new JButton("Delete");
		btnDeleteSaleline.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				EventQueue.invokeLater(new Runnable() {
					public void run() {
						try {
							JFrame deleteSalelineFrame = deleteSalelinePopupWindow();
							deleteSalelineFrame.setVisible(true);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			}
		});

		salelineChoicePanel.add(btnAddSaleline);
		salelineChoicePanel.add(btnDeleteSaleline);

		CardLayout cl = (CardLayout) salePanel.getLayout();
		cl.show(salePanel, "createSalePanel");

	}

	public JPanel createSaleInfoPanel() {
		JPanel saleInfoPanel = new JPanel();
		saleInfoPanel.setBorder(BorderFactory.createTitledBorder("Sale Info"));
		GroupLayout gl = new GroupLayout(saleInfoPanel);
		saleInfoPanel.setLayout(gl);
		gl.setAutoCreateGaps(true);
		gl.setAutoCreateContainerGaps(true);

		textField_saleId = new JTextField();
		textField_customerId = new JTextField();
		textField_invoiceId = new JTextField();
		textField_date = new JTextField();
		textField_deliveryStatus = new JTextField();
		textField_deliveryDate = new JTextField();
		
		//TODO
		cbbDeliveryStatus = new JComboBox(listStrings);
		cbbDeliveryStatus.setSelectedIndex(0);
		cbbDeliveryStatus.addActionListener(this);

		textField_customerId.setColumns(8);
		textField_invoiceId.setColumns(8);
		textField_date.setColumns(8);
		textField_deliveryDate.setColumns(8);
		textField_deliveryStatus.setColumns(8);

		gl.setHorizontalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(lblCustomerId)
								.addComponent(lblInvoiceId)
								.addComponent(lblDate)
								.addComponent(lblDeliveryStatus)
								.addComponent(lblDeliveryDate)
								)
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(textField_customerId)
								.addComponent(textField_invoiceId)
								.addComponent(textField_date)
								.addComponent(cbbDeliveryStatus)
								.addComponent(textField_deliveryDate)
								));
		gl.setVerticalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblCustomerId)
								.addComponent(textField_customerId))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblInvoiceId)
								.addComponent(textField_invoiceId))

				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblDate)
								.addComponent(textField_date))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblDeliveryStatus)
								.addComponent(cbbDeliveryStatus))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblDeliveryDate)
								.addComponent(textField_deliveryDate))
								);

		return saleInfoPanel;
	}

	public void showAllSale() {
		ArrayList<Sale> sales = saleCtr.getAllSale();
		saleTableModel.setRowCount(0);
		for (Sale sale : sales) {
			try {

				saleTableModel.addRow(new Object[] {
						sale.getSaleId(),
						sale.getInvoice().getInvoiceNo(),
						sale.getCustomer().getId(),
						convertDate(sale.getDate()),
						sale.getDeliverStatus().toString(),
						convertDate(sale.getDeliveryDate()),
						Double.valueOf(new DecimalFormat("#.##").format(sale
								.getTotalPrice())) });
			} catch (Exception e) {
				JOptionPane.showMessageDialog(null, e, "Error",
						JOptionPane.ERROR_MESSAGE);
			}

		}
		
		CardLayout cl = (CardLayout) salePanel.getLayout();
		cl.show(salePanel, "showAllSalePanel");
	}

	private void addSaleTable() {
		saleTableModel = new DefaultTableModel() {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		saleTableModel.addColumn("ID");
		saleTableModel.addColumn("Invoice No.");
		saleTableModel.addColumn("Customer ID");
		saleTableModel.addColumn("Date");
		saleTableModel.addColumn("Delivery");
		saleTableModel.addColumn("Delivery Date");
		saleTableModel.addColumn("Total Price");

		saleTableScrollPane = new JScrollPane();
		showAllSalePanel.add(saleTableScrollPane);
		showAllSaleTable = new JTable(saleTableModel);
		showAllSaleTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		showAllSaleTable.setAutoCreateRowSorter(true);

		showAllSaleTable.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				int row = showAllSaleTable.rowAtPoint(e.getPoint());
				if (e.getClickCount() == 2) {
					if (showSale(Integer.valueOf((Integer) showAllSaleTable
							.getValueAt(row, 0)))) {
						textField_saleIdMenu.setText((String.valueOf((Integer) showAllSaleTable
							.getValueAt(row, 0))));
					}
				}
			}
		});
		saleTableScrollPane.setViewportView(showAllSaleTable);
	}

	private JScrollPane showSalelineTable() {
		saleLineTableModel = new DefaultTableModel() {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		saleLineTableModel.addColumn("Product Id");
		saleLineTableModel.addColumn("Product ");
		saleLineTableModel.addColumn("Quantity");
		saleLineTableModel.addColumn("Sale Price");
		saleLineTableModel.addColumn("Subtotal Price");

		saleTableScrollPane = new JScrollPane();
		showSalelineTable = new JTable(saleLineTableModel);
		showSalelineTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		showSalelineTable.setAutoCreateRowSorter(true);

		saleTableScrollPane.setViewportView(showSalelineTable);
		return saleTableScrollPane;
	}

	public JFrame addSalelinePopupWindow() {
		final JFrame addSalelinePupupWindow = new JFrame("Add SaleLine");
		addSalelinePupupWindow.setSize(450, 100);
		addSalelinePupupWindow.setLocationRelativeTo(null);
		JLabel productBarcode = new JLabel("Product Id:");
		JLabel productQuantity = new JLabel("Quantity:");
		textField_ProductId = new JTextField();
		textField_ProductId.setColumns(8);
		textField_ProductQuantity = new JTextField();
		textField_ProductQuantity.setColumns(8);
		JButton btnAddSalelineOK = new JButton("OK");
		btnAddSalelineOK.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// read from product and append to hashmap products

				try {
					products.put(
							Integer.parseInt(textField_ProductId.getText()),
							Integer.parseInt(textField_ProductQuantity
									.getText()));
					showSaleline();

					showSalelineTable.revalidate();
					showSalelineTable.repaint();
					addSalelinePupupWindow.dispose();
				} catch (NumberFormatException e1) {
					JOptionPane.showMessageDialog(null,
							"Please input product Id and quantity.", "Error",
							JOptionPane.ERROR_MESSAGE);
				} catch (Exception e1) {
					JOptionPane.showMessageDialog(null, e1, "Error",
							JOptionPane.ERROR_MESSAGE);
				}
			}
		});
		JButton btnAddSalelineCancel = new JButton("Cancel");
		btnAddSalelineCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				addSalelinePupupWindow.dispose();
			}
		});

		JPanel addSalelinePanel = new JPanel();
		addSalelinePanel.setLayout(new BoxLayout(addSalelinePanel,
				BoxLayout.Y_AXIS));
		JPanel addSalelineInfoPanel = new JPanel();
		addSalelineInfoPanel.setLayout(new FlowLayout());
		JPanel addSalelineChoicePanel = new JPanel();
		addSalelineChoicePanel.setLayout(new FlowLayout());

		addSalelinePupupWindow.getContentPane().add(addSalelinePanel);
		addSalelinePanel.add(addSalelineInfoPanel);
		addSalelinePanel.add(addSalelineChoicePanel);
		addSalelineInfoPanel.add(productBarcode);
		addSalelineInfoPanel.add(textField_ProductId);
		addSalelineInfoPanel.add(productQuantity);
		addSalelineInfoPanel.add(textField_ProductQuantity);
		addSalelineChoicePanel.add(btnAddSalelineOK);
		addSalelineChoicePanel.add(btnAddSalelineCancel);

		return addSalelinePupupWindow;
	}

	private JFrame deleteSalelinePopupWindow() {
		final JFrame deleteSalelineWindow = new JFrame("Delete SaleLine");
		deleteSalelineWindow.setSize(500, 100);
		deleteSalelineWindow.setLocationRelativeTo(null);
		JLabel productBarcode = new JLabel("product Id:");
		textField_ProductId = new JTextField();
		textField_ProductId.setColumns(8);
		JButton btnDeleteSalelineOK = new JButton("OK");
		btnDeleteSalelineOK.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// delete in hashmap products and retrieve product
				try {
					products.remove(Integer.parseInt(textField_ProductId
							.getText()));
					showSaleline();
					showSalelineTable.revalidate();
					showSalelineTable.repaint();
					deleteSalelineWindow.dispose();
				} catch (Exception e1) {
					JOptionPane.showMessageDialog(null, e1, "Error",
							JOptionPane.ERROR_MESSAGE);
				}

			}
		});
		JButton btnDeleteSalelineCancel = new JButton("Cancel");
		btnDeleteSalelineCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				deleteSalelineWindow.dispose();
			}
		});
		JPanel deleteSalelinePanel = new JPanel();
		JPanel deleteSalelineInfoPanel = new JPanel();
		JPanel deleteSalelineChoicePanel = new JPanel();

		deleteSalelinePanel.setLayout(new BoxLayout(deleteSalelinePanel,
				BoxLayout.Y_AXIS));
		deleteSalelineInfoPanel.setLayout(new FlowLayout());
		deleteSalelineChoicePanel.setLayout(new FlowLayout());

		deleteSalelineWindow.getContentPane().add(deleteSalelinePanel);
		deleteSalelinePanel.add(deleteSalelineInfoPanel);
		deleteSalelinePanel.add(deleteSalelineChoicePanel);
		deleteSalelineInfoPanel.add(productBarcode);
		deleteSalelineInfoPanel.add(textField_ProductId);
		deleteSalelineChoicePanel.add(btnDeleteSalelineOK);
		deleteSalelineChoicePanel.add(btnDeleteSalelineCancel);

		return deleteSalelineWindow;
	}

	// show offer saleline in the table
	private void showSaleline() {
		Set<Integer> productIds = products.keySet();
		totalPrice = 0;

		try {
			ArrayList<Product> slProducts = new ArrayList<Product>();
			for (Integer productId : productIds) {
				slProducts.add(productCtr.getProduct(productId));
			}

			for (Product product : slProducts) {
				totalPrice = totalPrice + product.getSalePrice()
						* products.get(product.getProductId());
			}
			saleLineTableModel.setRowCount(0);
			for (Product product : slProducts) {
				saleLineTableModel.addRow(new Object[] {
						product.getProductId(),
						product.getName(),
						products.get(product.getProductId()),
						product.getSalePrice(),
						product.getSalePrice()
								* products.get(product.getProductId()) });
			}

			String[] space = { "", "", "", "", "" };
			String[] totalPriceRow = { "", "", "", "Total Price:",
					String.valueOf(totalPrice) };
			saleLineTableModel.addRow(space);
			saleLineTableModel.addRow(space);
			saleLineTableModel.addRow(totalPriceRow);
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e, "Error",
					JOptionPane.ERROR_MESSAGE);
		}

	}

	public void deleteSaleActionPerformed(ActionEvent e) {
		int reply = JOptionPane.showConfirmDialog(null,
				"Do you want to delete this Sale ?", "Delete Sale",
				JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
		if (reply == JOptionPane.YES_OPTION) {
			boolean success = true;
			try {
				saleCtr.deleteSale(Integer.parseInt(textField_saleIdMenu
						.getText()));
				textField_saleIdMenu.setText("");
				cleanTextField();
			} catch (NumberFormatException e1) {
				success = false;
				JOptionPane.showMessageDialog(null, "Field value invalid",
						"Error", JOptionPane.ERROR_MESSAGE);
			} catch (Exception e1) {
				success = false;
				JOptionPane.showMessageDialog(null, e1, "Error",
						JOptionPane.ERROR_MESSAGE);
			}
			if (success) {
				JOptionPane.showMessageDialog(null, "The Sale is deleted",
						"Delete Offer", JOptionPane.INFORMATION_MESSAGE);
				showAllSale();
			}
		}
	}

	public void cleanTextField() {
		textField_customerId.setText("");
		textField_invoiceId.setText("");
		textField_date.setText("");
		cbbDeliveryStatus.setSelectedIndex(0);
		textField_deliveryDate.setText("");
		textField_saleIdMenu.setText("");
	}

	public String convertDate(Date date) {
		DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
		return df.format(date);
	}

	public long getCurrentDate() {
		Calendar cal = Calendar.getInstance();
		java.util.Date utilDate = cal.getTime();
		return utilDate.getTime();
	}

	// convert date from long to string type
	public String convertDate(long date) {
		String orderDate = new SimpleDateFormat("dd/MM/yyyy").format(new Date(
				date));
		return orderDate;
	}
	
	public void selectDeliveryType(String type) {
		if (type.equals("NotDelivered")) {
			cbbDeliveryStatus.setSelectedIndex(0);
		} else if (type.equals("IsDelivered")) {
			cbbDeliveryStatus.setSelectedIndex(1);
		} else {
			cbbDeliveryStatus.setSelectedIndex(2);
		}
	}
	
	public void actionPerformed(ActionEvent e) {
		JComboBox cb = (JComboBox) e.getSource();
		String list = (String) cb.getSelectedItem();
	}

}
